package com.ruoyi.web.controller.project.fujian;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.project.fujian.domain.bo.AFujianBo;
import com.ruoyi.project.fujian.domain.vo.AFujianVo;
import com.ruoyi.project.fujian.service.IAFujianService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件
 *
 * @author ruoyi
 * @date 2024-03-02
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/project/fujian")
public class AFujianController extends BaseController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/file/upload/{type}")
    public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file,
                                         @PathVariable("type") String type
    ) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("File is empty.");
        }
        // 获取文件原名
        String originalFilename = file.getOriginalFilename();
        // 判断当前地址是否存在，不存在则创建
        Path filePath = Paths.get(uploadPath);
        // 判断路径是否存在
        if (!Files.exists(filePath)) {
            // 如果路径不存在，则尝试创建目录（假设uploadPath是指向目录的）
            Files.createDirectories(filePath);
        }
        // 构建新的文件名和目标路径
        Path targetLocation = Paths.get(uploadPath, originalFilename);
        // 将文件保存到指定目录
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        // 上传后将文件数据添加到文件数据库
        AFujianBo aFujianBo = new AFujianBo();
        aFujianBo.setFjid(IdUtil.simpleUUID());  //设置附件id
        aFujianBo.setFjname(originalFilename);   //设置附件名称
        aFujianBo.setFjpath("/"+originalFilename);  //设置附件路径
        aFujianBo.setFjtype(originalFilename.substring(originalFilename.lastIndexOf(".")));
        aFujianBo.setCreateusername(getUsername()); //获取用户名称
        aFujianBo.setCreateuserid(getUserId().toString()); //获取用户id
        aFujianBo.setCreatedeptname(getLoginUser().getDeptName());  //获取用户部门名称
        aFujianBo.setCreatedeptid(getDeptId().toString());  //获取用户部门id
        aFujianBo.setCreatetime(new Date());
        iAFujianService.insertByBo(aFujianBo);
        JSONObject entries = JSONUtil.parseObj(aFujianBo);
        entries.put("type", type);
        entries.put("name", originalFilename);
        return ResponseEntity.ok(entries);
    }

    private final IAFujianService iAFujianService;

    /**
     * 查询附件列表
     */
    @SaCheckPermission("project:fujian:list")
    @GetMapping("/list")
    public TableDataInfo<AFujianVo> list(AFujianBo bo, PageQuery pageQuery) {
        return iAFujianService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出附件列表
     */
    @SaCheckPermission("project:fujian:export")
    @Log(title = "附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(AFujianBo bo, HttpServletResponse response) {
        List<AFujianVo> list = iAFujianService.queryList(bo);
        ExcelUtil.exportExcel(list, "附件", AFujianVo.class, response);
    }

    /**
     * 获取附件详细信息
     *
     * @param fjid 主键
     */
    @SaCheckPermission("project:fujian:query")
    @GetMapping("/{fjid}")
    public R<AFujianVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String fjid) {
        return R.ok(iAFujianService.queryById(fjid));
    }

    /**
     * 新增附件
     */
    @SaCheckPermission("project:fujian:add")
    @Log(title = "附件", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody AFujianBo bo) {
        return toAjax(iAFujianService.insertByBo(bo));
    }

    /**
     * 修改附件
     */
    @SaCheckPermission("project:fujian:edit")
    @Log(title = "附件", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody AFujianBo bo) {
        return toAjax(iAFujianService.updateByBo(bo));
    }

    /**
     * 删除附件
     *
     * @param fjids 主键串
     */
    @SaCheckPermission("project:fujian:remove")
    @Log(title = "附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fjids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] fjids) {
        return toAjax(iAFujianService.deleteWithValidByIds(Arrays.asList(fjids), true));
    }
}
